/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import {
  MULTI_SOLUTION_SCHEMA,
  MultiSolutionWidget,
} from '@app-cad/common/components/command-form/widgets/multi-solution';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { useTools } from '@app-cad/common/hooks/useTools';
import { MessageTip } from '@app-cad/common/utils/MessageTip';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';
import { ctx2 } from '@app-cad/module';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { useEffect, useMemo, useState } from 'react';
import { usePointContext } from './PointContext';
import { ChildLineCommandProps } from './types';

type FormDataType = {
  curve: pickedLineData;
  vector: pickedLineData | pickedFaceData;
  keepAllSolution: boolean;
};

export function PointCurveTangency({
  onClose,
  props,
  editDxid,
}: ChildLineCommandProps) {
  const [formData, setFormData] = useState<FormDataType>({
    curve: null,
    vector: null,
    keepAllSolution: true,
  });
  const [solutionNum, setSolutionNum] = useState(0);
  const [solution, setSolution] = useState(0);
  const { setSharedPoint } = usePointContext();

  const { picker } = useTools();

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const curve = props?.params?.curve;
      const vector = props?.params?.vector;
      const keepAllSolution = props?.params?.keepAllSolution;
      const paramSolution = props?.params?.solution;

      await initEditDependency([curve, vector]);

      setFormData({
        curve: picker.generatePickObjByPickID(curve) as pickedLineData,
        vector: picker.generatePickObjByPickID(vector) as
          | pickedLineData
          | pickedFaceData,
        keepAllSolution: keepAllSolution,
      });

      setSolution(paramSolution);
    }
  }, [editDxid, props]);

  const isFormDataValid = () => {
    const { curve, vector } = formData;
    return vector !== null && curve !== null;
  };

  const checkAndFinishDraw = async () => {
    if (!isFormDataValid()) {
      return;
    }

    await execute(false);

    onClose();
  };

  const {
    previewCmdResult,
    initEditDependency,
    initingEdit,
    confirmCommand,
    clear,
    isLoading,
  } = useCommand('cmd-curve-tangency-point', {
    commandName: 'CreateVertex',
    editDxid: editDxid || props?.shape,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  useEffect(() => {
    const total = previewCmdResult?.data?.[0]?.points?.length || 0;
    const pointdata = previewCmdResult?.data?.[0]?.points?.[0];
    // console.log('result points total = ' + total);
    if (pointdata && total == 1) {
      setSharedPoint(pointdata);
    } else {
      setSharedPoint(null);
    }
  }, [previewCmdResult]);

  const execute = (preview: boolean) => {
    const { vector, curve, keepAllSolution } = formData;
    return confirmCommand(
      {
        a: {
          mode: 'curve-tangency',
          curve: curve?.edgeId,
          vector: getIdOfPickedObj(vector),
          solution: keepAllSolution ? -1 : solution,
          keepAllSolution: keepAllSolution,
        },
      },
      preview,
    );
  };

  const preview = async () => {
    if (!isFormDataValid()) {
      clear();
      setSolution(0);
      setSolutionNum(0);
      return;
    }

    const result = await execute(true);

    if (result?.nsolution <= 0) {
      MessageTip.warning('此运算没有任何解法');
    } else {
      setSolutionNum(result?.nsolution ?? 1);
    }

    ctx2.viewer.requestRender();
  };

  useAsyncEffect(preview, [solution]);

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      curve: {
        type: 'string',
        title: '曲线',
        format: PickInputRJSFFormat.PickCurve,
      },
      vector: {
        type: 'string',
        title: '方向',
        format: PickInputRJSFFormat.PickDirection,
      },
      keepAllSolution: {
        type: 'boolean',
        title: '保留所有解',
      },
      ...(formData?.keepAllSolution == false && solutionNum > 0
        ? { solution: MULTI_SOLUTION_SCHEMA }
        : {}),
    },
  };

  const finalFormData = useMemo(
    () => ({
      ...formData,
      solution: [solution, solutionNum],
    }),
    [formData, solution, solutionNum],
  );

  return (
    <NonDialogPickableCommandForm
      className='-mt-3'
      onCancel={onClose}
      disabled={initingEdit}
      submitLoading={isLoading}
      isFormDataValid={isFormDataValid()}
      schema={schema}
      formData={finalFormData}
      onChange={(v) => {
        const data = {
          curve: v.curve,
          vector: v.vector,
          keepAllSolution: v.keepAllSolution,
        };
        let solution = v.solution[0];
        if (v.keepAllSolution === false && solution === -1) {
          solution = 0;
        }
        setFormData(data);
        setSolution(solution);
      }}
      extraUiSchema={{
        curve: {
          'ui:placeholder': '请输入曲线',
          'ui:autofocus': true,
          'ui:options': {
            pickFilter: (obj) => {
              if (obj?.assisObj?.getType?.() === 'PickLine') {
                MessageTip.warning('曲线不能选择直线');
                return false;
              }
              return true;
            },
          },
        },
        vector: {
          'ui:placeholder': '方向',
        },
        keepAllSolution: {
          'ui:widget': 'checkbox',
          'ui:placeholder': '保留',
        },
        solution: {
          'ui:widget': MultiSolutionWidget,
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
    />
  );
}
